<template>
  <div class="list-pages white-bg">
    <div class="search-form-box">
      <a-form :model="formState" name="horizontal_login" :label-col="labelCol" autocomplete="off" @finish="onFinish">
        <a-row :gutter="[16, 16]">
          <a-col :xs="24" :sm="24" :md="12" :lg="6" :xl="6" v-show="expand">
            <a-form-item label="" name="name">
              <a-input v-model:value="formState.name" placeholder="请输入会员姓名和账号">
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="12" :lg="6" :xl="6">
            <a-form-item>
              <div class="search-btn-box" :class="{ pt: expand }">
                <a-button :icon="h(SearchOutlined)" type="primary" html-type="submit" class="search-btn"
                  @click="fetchMembershipData">查询</a-button>
                <a-button :icon="h(ReloadOutlined)" class="reset-btn" @click="resetForm">清空</a-button>
                <a-button 
                  type="default" 
                  :loading="exportLoading" 
                  @click="handleExport"
                  style="margin-left: 8px;"
                >
                  导出
                </a-button>
                <a class="expand-btn" style="font-size: 12px; margin-left: 12px" @click="expand = !expand">
                  <template v-if="expand">
                    <UpOutlined />
                  </template>
                  <template v-else>
                    <DownOutlined />
                  </template>
                  {{ expand ? "收起查询" : "展开查询" }}
                </a>
              </div>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <div class="table-wrapper" ref="tableRef">
      <a-table class="table-box" row-key="index" :columns="columns" :dataSource="tableData" :row-class-name="(_record, index) => (index % 2 === 1 ? 'table-striped' : null)
        " sticky :scroll="{ y: true, x: 1220 }" :pagination="pagination" @change="onChange">
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex == 'status'">
            <div class="cell-status-box" :class="{ 'is-active': record.status === 0 }">
              <div class="status-dot"></div>
              <div class="status-text">
                {{ record.status === 0 ? "已完成" : "未完成" }}
              </div>
            </div>
          </template>

          <template v-if="column.dataIndex == 'operation'">
            <a-button type="link" class="link" @click="handleDetail(record)">
              查看
            </a-button>
            <a-button 
              type="link" 
              class="link" 
              :loading="record.updating"
              @click="handleToggleStatus(record)"
            >
              {{ record.status === 0 ? '禁用' : '启用' }}
            </a-button>
          </template>
        </template>
      </a-table>
    </div>
  </div>
</template>
<script setup>
import { ref, computed, h, onMounted, onUnmounted } from "vue";
import {
  SearchOutlined,
  ReloadOutlined,
  DownOutlined,
  UpOutlined,
} from "@ant-design/icons-vue";
import { useRouter } from "vue-router";
import { useGlobalStore } from "@/store/modules/global";
import { message } from "ant-design-vue";
import administratorApi from "@/api/administrator";
const store = useGlobalStore();
const router = useRouter();
const labelCol = { style: { width: "80px" } };

const formState = ref({
  membershipStrategy: "",
  name: "",
  class: [],
  zone: "",
  status: [],
  partner: [],
});

// 下拉选项数据
const membershipStrategyOptions = ref([]);
const equipmentOptions = ref([]);
const statusOptions = ref([
  { value: "0", label: "已完成", tag: "success", text: "已完成" },
  { value: "1", label: "未完成", tag: "warning", text: "未完成" },
]);
const customerOptions = ref([]);

// 导出相关
const exportLoading = ref(false);
// 获取会员策略下拉选项
const fetchMembershipStrategyOptions = async (keyWords = "") => {
  try {
    const params = {
      keyWords: keyWords
    };
    const response = await administratorApi.MembershipStrategyOptions(params);
    if (response) {
      membershipStrategyOptions.value = response;
    }
  } catch (error) {
    console.error("获取会员策略下拉选项失败:", error);
  }
};

// 获取设备下拉选项
const fetchEquipmentOptions = async (keyWords = "") => {
  try {
    const params = {
      keyWords: keyWords
    };
    const response = await administratorApi.ExperimentEquipmentOptions(params);
    if (response) {
      equipmentOptions.value = response;
    }
  } catch (error) {
    console.error("获取设备下拉选项失败:", error);
  }
};

// 获取客户下拉选项
const fetchCustomerOptions = async (keyWords = "") => {
  try {
    const params = {
      keyWords: keyWords
    };
    const response = await administratorApi.CustomerOptions(params);
    if (response) {
      customerOptions.value = response;
    }
  } catch (error) {
    console.error("获取客户下拉选项失败:", error);
  }
};

const resetForm = () => {
  formState.value = {
    membershipStrategy: "",
    name: "",
    class: [],
    zone: "",
    status: [],
    partner: [],
  };
  current.value = 1; // 重置到第一页
  fetchMembershipData(); // 重置后重新获取数据
};
const windowWidth = ref(window.innerWidth);
const expand = ref(true);
onMounted(() => {
  windowWidth.value = window.innerWidth;
  if (windowWidth.value > 768) {
    expand.value = true;
  } else {
    expand.value = false;
  }
  window.addEventListener("resize", () => {
    windowWidth.value = window.innerWidth;
    if (windowWidth.value > 768) {
      expand.value = true;
    } else {
      expand.value = false;
    }
  });
  
  // 初始化数据
  fetchMembershipData(); // 初始化时获取会员数据
  fetchMembershipStrategyOptions(); // 获取会员策略下拉选项
  fetchEquipmentOptions(); // 获取设备下拉选项
  fetchCustomerOptions(); // 获取客户下拉选项
});
onUnmounted(() => {
  window.removeEventListener("resize", () => { });
});

function onFinish(values) {
  console.log("Success:", values);
}
const tableData = ref([]);

// 获取会员数据
const fetchMembershipData = async () => {
  try {
    console.log("开始获取会员数据...");
    const params = {
      args: {
        current: current.value,
        pageSize: pageSize.value,
        key: "",
        keyword: formState.value.name || "",
        idArray: [],
        categoryId: "",
        enabled: undefined,
        dateRange: []
      },
      sort: {},
      filter: {}
    };

    console.log("API请求参数:", params);
    const response = await administratorApi.MembershipPagedList(params);
    console.log("API响应数据:", response);

    if (response.data && Array.isArray(response.data) && response.data.length > 0) {
      console.log("开始映射数据...");
      // 将会员数据映射到现有的表格字段结构
      tableData.value = response.data.map((item, index) => ({
        no: item.user?.real_name || `会员${index + 1}`,
        name: item.user?.login_name || "未知账号",
        class: item.user?.weixins && item.user.weixins.length > 0 ? "已绑定" : "未绑定",
        zone: item.user?.create_time ? new Date(item.user.create_time).toLocaleDateString() : new Date().toLocaleDateString(),
        status: item.enabled ? 0 : 1, // 0表示已完成(激活)，1表示未完成(未激活)
        orders: item.created ? new Date(item.created).toLocaleDateString() : "未激活",
        strategy: item.strategy?.name || "基础策略",
        partner: item.enabled ? "正常" : "禁用",
        date: item.created || new Date().toISOString(),
        user_id: item.user_id, // 保存用户ID用于详情页面跳转
        membership_id: item.id, // 保存会员ID用于更新
        membershipData: item, // 保存完整的会员数据
        updating: false, // 添加更新状态
      }));
      total.value = response.total || response.data.length;
      console.log("映射后的表格数据:", tableData.value);
      console.log("总数:", total.value);
    } else {
      console.log("API响应格式不正确或无数据，清空表格");
      // 没有数据时清空表格
      tableData.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error("获取会员数据失败:", error);
    // 接口调用失败时也清空表格
    tableData.value = [];
    total.value = 0;
  }
};

const columns = ref([
  {
    dataIndex: "no",
    title: "会员姓名",
    width: 120,
  },
  {
    dataIndex: "name",
    title: "注册账号",
    width: 120,
  },
  {
    dataIndex: "class",
    title: "绑定微信",
    width: 110,
    
  },
  {
    dataIndex: "zone",
    title: "注册日期",
    width: 120,
  },
  {
    dataIndex: "orders",
    title: "会员激活日期",
    width: 120,
  },
  {
    dataIndex: "strategy",
    title: "使用策略",
    width: 120,
  },
  {
    dataIndex: "partner",
    title: "当前状态",
    width: 120,
  },
  {
    dataIndex: "operation",
    title: "操作",
    width: 160,
    align: "center",
    fixed: "right",
  },
]);

const onChange = (page) => {
  console.log(page);
  current.value = page.current;
  pageSize.value = page.pageSize;
  fetchMembershipData(); // 分页变化时重新获取数据
};
const current = ref(1);
const pageSize = ref(10);
const total = ref(0);
const pagination = computed(() => ({
  position: ["bottomCenter"],
  total: total.value,
  current: current.value,
  pageSize: pageSize.value,
  showSizeChanger: true,
  size: "large",
  showTotal: (total) => `共 ${total} 条`,
}));


const handleDetail = (data) => {
  store.setSubTitle("会员详情");
  router.push({
    path: "member-management-detail",
    query: { user_id: data.user_id || data.no }
  });
};
const handleToggleStatus = async (record) => {
  try {
    // 设置更新状态
    record.updating = true;
    
    // 获取会员详情数据
    const detailParams = {
      // id: record.membership_id
      user_id: record.user_id
    };
    
    console.log("获取会员详情参数:", detailParams);
    const detailResponse = await administratorApi.MembershipFetchModel(detailParams);
    console.log("会员详情响应:", detailResponse);
    
    if (!detailResponse) {
      message.error("获取会员详情失败");
      return;
    }
    
    // 构建更新数据，保持原有结构不变，只更新enabled字段
    const updateData = {
      ...detailResponse,
      enabled: !detailResponse.enabled // 切换启用状态
    };
    
    console.log("更新会员数据:", updateData);
    
    // 调用更新接口
    const updateResponse = await administratorApi.MembershipUpdate(updateData);
    console.log("更新响应:", updateResponse);
    
    if (updateResponse) {
      message.success(`${detailResponse.enabled ? '禁用' : '启用'}成功`);
      // 重新获取数据刷新列表
      await fetchMembershipData();
    } else {
      message.error("操作失败，请稍后重试");
    }
  } catch (error) {
    console.error("切换会员状态失败:", error);
    message.error("操作失败，请稍后重试");
  } finally {
    // 清除更新状态
    record.updating = false;
  }
};

// 导出会员列表
const handleExport = async () => {
  try {
    exportLoading.value = true;
    
    // 构建导出参数，使用当前搜索条件
    const exportParams = {
      args: {
        current: current.value,
        pageSize: pageSize.value,
        key: "",
        keyword: formState.value.name || "",
        idArray: [],
        categoryId: "",
        enabled: undefined,
        dateRange: formState.value.zone || []
      },
      sort: {},
      filter: {}
    };
    
    console.log("导出参数:", exportParams);
    
    // 调用导出API
    const response = await administratorApi.MembershipExport(exportParams);
    
    console.log("导出响应:", response);
    
    if (response && response.file) {
      const fileData = response.file;
      
      // 处理Base64编码的文件内容
      const base64Content = fileData.fileContents;
      const contentType = fileData.contentType || 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
      const fileName = fileData.fileDownloadName || '会员列表_导出.xlsx';
      
      try {
        // 将Base64字符串转换为二进制数据
        const binaryString = atob(base64Content);
        const bytes = new Uint8Array(binaryString.length);
        for (let i = 0; i < binaryString.length; i++) {
          bytes[i] = binaryString.charCodeAt(i);
        }
        
        // 创建Blob对象
        const blob = new Blob([bytes], { type: contentType });
        
        // 创建下载链接
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = fileName;
        
        // 触发下载
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        
        // 清理URL对象
        window.URL.revokeObjectURL(url);
        
        message.success("导出成功");
      } catch (decodeError) {
        console.error("文件解码失败:", decodeError);
        message.error("文件解码失败，请稍后重试");
      }
    } else {
      const errorMessage = response?.errors?.[0] || "导出失败";
      console.error("导出失败:", response);
      message.error(errorMessage);
    }
  } catch (error) {
    console.error("导出会员列表失败:", error);
    message.error("导出失败，请稍后重试");
  } finally {
    exportLoading.value = false;
  }
};

</script>
<style lang="less" scoped>
.list-pages {
  height: 100%;
  padding: 0 16px;
  display: flex;
  flex-direction: column;

  .search-box {
    display: flex;
    align-items: center;
    padding: 18px 0;
    flex-wrap: wrap;
    border-bottom: 1px solid #e5e7eb;

    .search-select {
      width: 120px;
    }

    .line {
      width: 1px;
      height: 16px;
      margin: 0 12px;
      background: #bec4ca;

      @media screen and (max-width: 768px) {
        display: none;
      }
    }

    .search-input-box {
      flex: 1;
      display: flex;
      align-items: center;

      @media screen and (max-width: 768px) {
        width: 100%;
        margin-top: 16px;
        justify-content: space-between;
      }
    }

    .search-input {
      flex: 1;
    }

    .search-btn {
      width: 60px;
      height: 32px;
      background: #2776ff;
      border-radius: 4px;
      font-family: PingFangSC-Regular;
      font-weight: 400;
      font-size: 14px;
      color: #ffffff;
      text-align: center;
      line-height: 32px;
    }
  }

  // 下拉选项样式
  :deep(.ant-select-dropdown) {
    .ant-select-item-option-content {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .success {
      color: #52c41a;
    }
    
    .warning {
      color: #faad14;
    }
    
    .error {
      color: #ff4d4f;
    }
  }

  .table-wrapper {
    width: 100%;
    flex: 1;
    overflow: hidden;

    .table-box {
      height: 100%;
    }
  }

  .list-box {
    width: 100%;
    box-sizing: border-box;
    padding-top: 16px;
    overflow: auto;
    display: grid;
    gap: 16px;
    margin: 0 auto;
    grid-template-columns: repeat(auto-fill, minmax(261px, 1fr));
    justify-content: space-between;

    .list-item {
      width: 261px;
      background: #ffffff;
      border: 1px solid #e6ebf1;
      border-radius: 8px;
      box-sizing: border-box;
      padding: 8px;
      margin: auto;
      position: relative;
      cursor: pointer;

      &:hover {
        border: 1px solid #2776ff;
        box-shadow: 12px 12px 12px 0px rgba(39, 118, 255, 0.1);
      }

      .item-collect {
        position: absolute;
        top: 0;
        right: 0;
        cursor: pointer;
        width: 32px;
        height: 32px;
        background: rgba(0, 0, 0, 0.4) url(@/assets/icon-collet.png) no-repeat center center;
        border-radius: 0 8px 0 12px;

        &.cur {
          background: #ffffff url(@/assets/icon-collet-cur.png) no-repeat center center;
          border-radius: 0 8px 0 12px;
        }
      }

      .list-img {
        width: 245px;
        height: 249px;
        background: #f3f3f3;
        border: 1px solid #e6ebf1;
        border-radius: 8px;
        box-sizing: border-box;

        img {
          width: 100%;
          height: 100%;
          border-radius: 8px;
        }
      }

      .list-content {
        padding: 14px 0 6px;
        display: flex;
        flex-direction: column;

        .content-title {
          font-family: PingFangSC-Medium;
          font-weight: 500;
          font-size: 16px;
          color: #31323a;
          margin-bottom: 10px;
          line-height: 24px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .content-col {
          display: flex;
          align-items: center;
          justify-content: space-between;

          .col-user {
            display: flex;
            align-items: center;

            .user-img {
              width: 26px;
              height: 26px;
              border-radius: 50%;
            }

            .user-name {
              font-family: PingFangSC, PingFang SC;
              font-weight: 400;
              font-size: 12px;
              color: #262626;
              line-height: 16px;
              text-align: left;
              font-style: normal;
            }
          }

          .col-date {
            font-family: PingFangSC, PingFang SC;
            font-weight: 400;
            font-size: 12px;
            color: #8c8c8c;
            line-height: 16px;
            text-align: center;
            font-style: normal;
          }
        }
      }
    }
  }

  .pagination-box {
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
